package com.wenhai.spring.bean.definition;


import com.wenhai.spring.bean.factory.DefaultUserFactory;
import com.wenhai.spring.bean.factory.UserFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @Author:wenhai
 * @Description: ServiceLoader
 * @Date:2020/3/6
 */
public class SpecialBeanInstantiationDemo {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/special-bean-instantiation-context.xml");
        AutowireCapableBeanFactory autowireCapableBeanFactory = context.getAutowireCapableBeanFactory();
        @SuppressWarnings("unchecked")
        ServiceLoader<UserFactory> userServiceLoaderFactoryBean = context.getBean("userFactoryServiceLoader", ServiceLoader.class);
        displayServiceLoaderElement(userServiceLoaderFactoryBean);
        serviceLoaderDemo();
        // 创建UserFactory对象通过AutowireCapableBeanFactory
        UserFactory userFactory = autowireCapableBeanFactory.createBean(DefaultUserFactory.class);
        System.out.println(userFactory.createUser());

    }

    public static void serviceLoaderDemo() {
        ServiceLoader<UserFactory> load = ServiceLoader.load(UserFactory.class, Thread.currentThread().getContextClassLoader());
        displayServiceLoaderElement(load);

    }

    public static void displayServiceLoaderElement(ServiceLoader<UserFactory> serviceLoader) {
        Iterator<UserFactory> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            UserFactory next = iterator.next();
            System.out.println(next.createUser());
        }
    }
}


